import * as THREE from "three";
import gsap from "gsap";

export default class Ship {
  constructor() {
    this.chairModels = [];
    this.bodyModels = [];
    this.main = new THREE.Group();

    this.rotation = -Math.PI / 2;

    gsap.timeline({ yoyo: true, repeat: -1 }).to(this, { rotation: Math.PI / 2, duration: 1.4, ease: "power1.inOut" });
  }

  add(mesh) {
    if (mesh.userData.name === "ship-chair") {
      this.chairModels.push(mesh);
    } else {
      this.bodyModels.push(mesh);
    }
  }

  build() {
    const defaultPosition = this.bodyModels[0].position.clone();
    this.bodyModels.map(model => {
      model.position.set(0, 0, 0);
      this.main.add(model);
    });
    this.main.position.copy(defaultPosition);

    const chair = new THREE.Group();
    const defaultChairPosition = this.chairModels[0].position.clone();
    this.chairModels.map(model => {
      model.position.set(0, 0, 0);
      chair.add(model);
    });
    const diffPosition = defaultChairPosition.sub(defaultPosition);
    chair.position.copy(diffPosition);
    this.main.add(chair);

    const mat = new THREE.Vector2(5, 3);
    const gap = new THREE.Vector2(.8, .7);

    for (let x = 0; x < mat.x; x++) {
      for (let y = 0; y < mat.y; y++) {
        if (x + y !== 0) {
          const n = chair.clone().translateX(gap.x * x).translateY(gap.y * y);
          this.main.add(n);
        }
      }
    }
  }

  update() {
    this.main.rotation.y = this.rotation;
  }
}